<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="生产主体" prop="productionEntity">
        <el-input
          v-model="queryParams.productionEntity"
          placeholder="请输入生产主体"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="检查时间" prop="inspectionTime">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="检查人员" prop="inspector">
        <el-input
          v-model="queryParams.inspector"
          placeholder="请选择"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- 省市区查询条件仅管理员可见 -->
      <template v-if="isAdmin">
        <el-form-item label="省" prop="province">
          <el-select v-model="queryParams.province" placeholder="请选择" clearable @change="handleProvinceChange">
            <el-option
              v-for="province in provinceOptions"
              :key="province.value"
              :label="province.label"
              :value="province.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="市" prop="city">
          <el-select v-model="queryParams.city" placeholder="请选择" clearable @change="handleCityChange">
            <el-option
              v-for="city in cityOptions"
              :key="city.value"
              :label="city.label"
              :value="city.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="区/县" prop="district">
          <el-select v-model="queryParams.district" placeholder="请选择区/县(请先选择市)" clearable>
            <el-option
              v-for="district in districtOptions"
              :key="district.value"
              :label="district.label"
              :value="district.value"
            />
          </el-select>
        </el-form-item>
      </template>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查询</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 省市区查询条件权限说明 -->
    <div v-if="showSearch && isAdmin" class="permission-tips">
      <el-alert
        title="查询条件权限说明"
        type="warning"
        :closable="false"
        show-icon>
        <div slot="description">
          <p><strong>省市区查询条件仅管理员可见</strong></p>
        </div>
      </el-alert>
    </div>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['nongjt:inspectionRecord:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['nongjt:inspectionRecord:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['nongjt:inspectionRecord:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="inspectionRecordList" @selection-change="handleSelectionChange" style="width: 100%">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="检查部门" align="center" prop="inspectionDepartment" min-width="200" show-overflow-tooltip />
      <el-table-column label="检查人员" align="center" prop="inspector" min-width="120" />
      <el-table-column label="生产主体" align="center" prop="productionEntity" min-width="200" show-overflow-tooltip />
      <el-table-column label="法人名称" align="center" prop="legalPersonName" min-width="120" />
      <el-table-column label="联系电话" align="center" prop="contactPhone" min-width="130" />
      <el-table-column label="省" align="center" prop="province" min-width="100" />
      <el-table-column label="市" align="center" prop="city" min-width="100" />
      <el-table-column label="区/县" align="center" prop="district" min-width="100" />
      <el-table-column label="镇/乡" align="center" prop="township" min-width="120" />
      <el-table-column label="检查地点" align="center" prop="inspectionLocation" min-width="150" show-overflow-tooltip />
      <el-table-column label="产品名称" align="center" prop="productName" min-width="120" />
      <el-table-column label="是否证照齐全" align="center" prop="licenseComplete" min-width="120">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.licenseComplete == 'qualified'" type="success">合格</el-tag>
          <el-tag v-else type="danger">不合格</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="是否使用禁用农药、兽药" align="center" prop="prohibitedDrugUsed" min-width="180">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.prohibitedDrugUsed == 'qualified'" type="success">合格</el-tag>
          <el-tag v-else type="danger">不合格</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="检查意见" align="center" prop="inspectionOpinion" min-width="150" show-overflow-tooltip />
      <el-table-column label="检查记录照片" align="center" prop="inspectionPhotos" min-width="120">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.inspectionPhotos"
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleViewPhotos(scope.row)"
          >查看</el-button>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="检查时间" align="center" prop="inspectionTime" min-width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.inspectionTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['nongjt:inspectionRecord:edit']"
          >编辑</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['nongjt:inspectionRecord:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-more"
            @click="handleMore(scope.row)"
          >更多</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改检查记录对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="检查人员" prop="inspector">
              <el-input v-model="form.inspector" placeholder="请输入检查人员" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="打印编号" prop="printNumber">
              <el-input v-model="form.printNumber" placeholder="请输入打印编号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="主体名称" prop="productionEntity">
              <el-input v-model="form.productionEntity" placeholder="请输入主体名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="法人" prop="legalPersonName">
              <el-input v-model="form.legalPersonName" placeholder="请输入法人" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="联系方式" prop="contactPhone">
              <el-input v-model="form.contactPhone" placeholder="请输入联系方式" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="检查产品" prop="productName">
              <el-input v-model="form.productName" placeholder="请输入检查产品" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="检查地点" prop="inspectionLocation">
              <el-input v-model="form.inspectionLocation" placeholder="请输入检查地点" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="检查时间" prop="inspectionTime">
              <el-date-picker clearable
                v-model="form.inspectionTime"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择检查时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="检查意见" prop="inspectionOpinion">
          <el-input v-model="form.inspectionOpinion" type="textarea" placeholder="请输入检查意见" />
        </el-form-item>
        <el-form-item label="检查记录照片" prop="inspectionPhotos">
          <el-upload
            class="upload-demo"
            :action="uploadUrl"
            :headers="uploadHeaders"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :on-remove="handleRemove"
            :file-list="fileList"
            :before-upload="beforeUpload"
            list-type="picture"
            multiple>
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过10MB</div>
          </el-upload>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="合格证开具是否规范" prop="certificateCompliant">
              <el-radio-group v-model="form.certificateCompliant">
                <el-radio label="qualified">合格</el-radio>
                <el-radio label="unqualified">不合格</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否使用禁限用农药" prop="restrictedPesticideUsed">
              <el-radio-group v-model="form.restrictedPesticideUsed">
                <el-radio label="qualified">合格</el-radio>
                <el-radio label="unqualified">不合格</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 检查记录照片查看对话框 -->
    <el-dialog title="检查记录照片" :visible.sync="photoOpen" width="80%" append-to-body>
      <div v-if="currentPhotos">
        <img v-for="(photo, index) in currentPhotos" :key="index" :src="photo" style="width: 100%; max-height: 600px; margin-bottom: 10px;" />
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listInspectionRecord, getInspectionRecord, delInspectionRecord, addInspectionRecord, updateInspectionRecord } from "@/api/monitor/njt/inspection/record";

export default {
  name: "InspectionRecord",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 检查记录表格数据
      inspectionRecordList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示照片查看弹出层
      photoOpen: false,
      // 当前查看的照片
      currentPhotos: null,
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        productionEntity: null,
        inspector: null,
        province: null,
        city: null,
        district: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        inspector: [
          { required: true, message: "检查人员不能为空", trigger: "blur" }
        ],
        productionEntity: [
          { required: true, message: "主体名称不能为空", trigger: "blur" }
        ],
        legalPersonName: [
          { required: true, message: "法人不能为空", trigger: "blur" }
        ],
        contactPhone: [
          { required: true, message: "联系方式不能为空", trigger: "blur" }
        ],
        productName: [
          { required: true, message: "检查产品不能为空", trigger: "blur" }
        ],
        inspectionLocation: [
          { required: true, message: "检查地点不能为空", trigger: "blur" }
        ],
        inspectionTime: [
          { required: true, message: "检查时间不能为空", trigger: "change" }
        ],
        inspectionOpinion: [
          { required: true, message: "检查意见不能为空", trigger: "blur" }
        ],
        certificateCompliant: [
          { required: true, message: "合格证开具是否规范不能为空", trigger: "change" }
        ],
        restrictedPesticideUsed: [
          { required: true, message: "是否使用禁限用农药不能为空", trigger: "change" }
        ]
      },
      // 文件列表
      fileList: [],
      // 文件上传配置
      uploadUrl: process.env.VUE_APP_BASE_API + '/common/uploads',
      uploadHeaders: {},
      // 省市区选项
      provinceOptions: [
        { label: '四川省', value: '四川省' }
      ],
      cityOptions: [],
      districtOptions: [],
      // 用户类型判断
      isAdmin: true
    };
  },
  created() {
    this.getList();
    this.initRegionData();
    this.checkUserType();
    this.initUploadHeaders();
  },
  methods: {
    /** 查询检查记录列表 */
    getList() {
      this.loading = true;
      listInspectionRecord(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.inspectionRecordList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        inspectionDepartment: null,
        inspector: null,
        productionEntity: null,
        legalPersonName: null,
        contactPhone: null,
        province: null,
        city: null,
        district: null,
        township: null,
        inspectionLocation: null,
        productName: null,
        licenseComplete: null,
        prohibitedDrugUsed: null,
        inspectionOpinion: null,
        inspectionPhotos: null,
        inspectionTime: null,
        printNumber: null,
        certificateCompliant: null,
        restrictedPesticideUsed: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.fileList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加检查记录";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getInspectionRecord(id).then(response => {
        this.form = response.data;
        // 处理已上传的照片
        if (this.form.inspectionPhotos) {
          const photos = this.form.inspectionPhotos.split(',');
          this.fileList = photos.map((photo, index) => ({
            name: `photo_${index + 1}.jpg`,
            url: photo,
            uid: Date.now() + index
          }));
        }
        this.open = true;
        this.title = "修改检查记录";
      });
    },
    /** 查看照片 */
    handleViewPhotos(row) {
      this.currentPhotos = row.inspectionPhotos ? row.inspectionPhotos.split(',') : [];
      this.photoOpen = true;
    },
    /** 更多按钮操作 */
    handleMore(row) {
      this.$message.info("更多功能开发中...");
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateInspectionRecord(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addInspectionRecord(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      const message = row.id ? '是否确认删除该检查记录？' : '是否确认删除选中的检查记录？';
      this.$modal.confirm(message).then(function() {
        return delInspectionRecord(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('nongjt/inspectionRecord/export', {
        ...this.queryParams
      }, `检查记录_${new Date().getTime()}.xlsx`)
    },
    // 文件上传相关
    beforeUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt10M = file.size / 1024 / 1024 < 10;

      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG/PNG 格式!');
        return false;
      }
      if (!isLt10M) {
        this.$message.error('上传图片大小不能超过 10MB!');
        return false;
      }
      return true;
    },
    handleUploadSuccess(response, file, fileList) {
      if (response.code === 200) {
        // 处理多文件上传成功
        const urls = response.urls.split(',');
        this.form.inspectionPhotos = urls.join(',');
        this.$message.success('文件上传成功');
      } else {
        this.$message.error(response.msg || '文件上传失败');
      }
    },
    handleUploadError(error, file, fileList) {
      this.$message.error('文件上传失败');
      console.error('Upload error:', error);
    },
    handleRemove(file, fileList) {
      // 重新构建照片路径字符串
      const urls = fileList.map(item => {
        if (item.response && item.response.url) {
          return item.response.url;
        } else if (item.url) {
          return item.url;
        }
        return null;
      }).filter(url => url);
      this.form.inspectionPhotos = urls.join(',');
    },
    // 初始化地区数据
    initRegionData() {
      this.cityOptions = [
        { label: '成都市', value: '成都市' }
      ];
      this.districtOptions = [
        { label: '郫都区', value: '郫都区' },
        { label: '新都区', value: '新都区' },
        { label: '温江区', value: '温江区' },
        { label: '天府新区', value: '天府新区' }
      ];
    },
    // 检查用户类型
    checkUserType() {
      // 这里应该根据当前登录用户判断用户类型
      this.isAdmin = true; // 管理员
    },
    // 初始化上传头部
    initUploadHeaders() {
      this.uploadHeaders = {
        'Authorization': 'Bearer ' + this.$store.getters.token
      };
    },
    // 省变化处理
    handleProvinceChange(value) {
      this.queryParams.city = null;
      this.queryParams.district = null;
    },
    // 市变化处理
    handleCityChange(value) {
      this.queryParams.district = null;
    }
  }
};
</script>

<style scoped>
.permission-tips {
  margin-bottom: 20px;
}

.permission-tips .el-alert {
  margin-bottom: 0;
}

.permission-tips p {
  margin: 5px 0;
  font-size: 14px;
}
</style>
